package com.peppa.common.grayconfig.Strategy;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.peppa.common.grayconfig.FeignHeaderRequestInterceptor;
import com.peppa.common.grayconfig.Strategy.factory.AnnoStrategy;
import com.peppa.common.grayconfig.ThreadAttributes;

/**
 * @author     ：杜戈
 * @date       ：Created in 2019.08.21
 * @description：服务器IP策略，服务器上的策略字符串中为一个正则，如果ip满足这个正则，则可以选择这个服务器
 */
@AnnoStrategy
public class ServerIpStrategy extends StrategyAbstract {
    private final String strategy_key = "gray-ip";

    public ServerIpStrategy() {
        setName(S_IP);
        setOrder(SORT_S_IP);
    }

    @Override
    public Server getServer(ILoadBalancer balancer){
        String ip = (String) ThreadAttributes.getThreadAttribute(FeignHeaderRequestInterceptor.HTTP_X_FORWARDED_FOR);
        if (ip == null || ip.equals("")){
            logger.info("HTTP_X_FORWARDED_FOR threadlocal ip:---null!!!");
            return null;
        }
        return getServerByRegex(balancer,ip,strategy_key);
    }
    @Override
    public String getName(){
        return name;
    }
}
